<template>
  <rx-fit class="user-list-fit" >
    <rx-grid
      ref="table"
      :allowRowSelect="true"
      :multiSelect="true"
      :columns="userColumns"
      :defaultPageSize="10"
      :dataSource="userData"
      @selectChange="onSelectUserChange"
      :pageSizeOptions="['10','30','40']"
      id-field="party2"
      :showPageSize="true"
      :showPageJump="false"
      :showPageEntry="true"
      :dataTotal="dataTotal"
      @onPageConfigChange="onPageConfigChange"
    >
        <span slot="action" slot-scope="{text, record}"  class="actionIcons">
            <span @click="handleUserEdit(record)" v-if="editEnabel">{{$ti18('rxList.editBtn','编辑')}}</span>
            <span @click="modifyPwd(record)" v-if="editEnabel" :title="i18n('list.changePwd','修改密码')">{{i18n('list.changePwd','修改密码')}}</span>
<!--统一用顶部的移除按钮就足够了，所以删掉这个-->
<!--            <span  @click="removeUser(record)">移除</span>-->
        </span>
    </rx-grid>
  </rx-fit>


</template>

<script>

import OsRelInstApi from '@/api/user/org/osRelInst'

import OsUserEdit from './OsUserEdit'
import {notification} from "ant-design-vue";
import {Util} from "@lowcode/jpaas-common-lib";
import { RxGrid,RxFit,Dialog } from "@lowcode/jpaas-common-lib"
import OsUserUpdatePwd from './OsUserUpdatePwd'

  export default {
    name: 'userListComponent',
    props: {
      relTypeId:String,
      groupId:String,
      isMain:String,
      tenantId:String,
      dimId:String,
      type:{
          type:[String,Number]
      }
    },
    components: {

        OsUserEdit,
        RxFit,
        RxGrid
    },
    data () {
      return {
        page:1,
        pageSize:10,
        dataTotal:0,
        visible: false,
        selectedUserRowKeys: [],
        selectedUserRows: [],
        userData: [],
        // 表头
        userColumns: [
          {
            title: this.i18n('form.name','姓名'),
            dataIndex: 'fullname',

          },
          {
            title: this.i18n('form.account','账号'),
            dataIndex: 'userNo',

          },
          {
            title: this.$ti18('rxList.action','操作'),
            dataIndex: 'action',
            scopedSlots: {customRender: 'action'}
          }
        ],
        editEnabel:true,
        params:{},
        action:'',

        // 表头
        adminColumns: [
          {
              title: this.i18n('form.name','姓名'),
              dataIndex: 'fullname',
              width:100
          },
          {
              title: this.i18n('form.account','账号'),
              dataIndex: 'userNo',
              width:120
          },
          {
              title: this.$ti18('rxList.action','操作'),
              dataIndex: 'action',
              scopedSlots: {customRender: 'adminAction'}
          }
        ]
      }
    },
    created () {
      this.init()
    },
    methods: {
      init(params,pageShow){
        var self_=this;
        if(params){
          this.params=params
        }
        if(pageShow){
            this.page = 1;
        }
        if(!this.groupId){
          this.userData = [];
        }else {
          const queryParams = Object.assign({}, {
            groupId: this.groupId,
            tenantId:this.tenantId,
            relTypeId: this.relTypeId, pageNum: this.page, pageSize: this.pageSize
          }, this.params);
          if(this.isMain){
            queryParams.isMain=this.isMain;
          }
          OsRelInstApi.getUserListByGroupIdAndRelTypeId(queryParams).then(res => {
              const data = res.data;
              self_.dataTotal=res.count;
              self_.$refs.table.setPageConfig(self_.page,self_.pageSize,self_.dataTotal);
              this.userData = data;
          })

        }
      },
      i18n(name,text,key){
          return this.$ti18(name,text,"UserListComponent",key);
      },
      //监听页面参数变化
      onPageConfigChange(p1, p2) {
          this.page = p1;
          this.pageSize = p2;
          this.init();
      },
      onSelectUserChange (selectedRowKeys, selectedRows) {
        this.selectedUserRowKeys = selectedRowKeys;
        this.selectedUserRows = selectedRows
      },
      handleUserEdit(record){
        var params={pkId:record.party2};
        if(this.tenantId){
            params.tenantId=this.tenantId;
        }
        var title = this.i18n('list.editTitle','编辑用户');
        var conf= {
          curVm:this,
          data:params,
          widthHeight:['800px', '600px'],
          component:OsUserEdit,
          title:title
        };
        Util.open(conf,function(action){
          this.$parent.init();
        });
      },
      removeUser(record) {
        this.unjoin(record.party2)
      },
      removeSelectUser(){
          let removeSelectUserTip=this.i18n('msa.removeSelectUserTip','请选择需要移除的用户');
          let tipTitle=this.i18n('msa.tipTitle','提示信息');
          let confirmRemove=this.i18n('msa.confirmRemove','确认将用户从关系中移除吗');
          let tipOk=this.i18n('msa.ok','确认');
          let tipCancel=this.i18n('msa.cancel','取消');

          if(this.selectedUserRowKeys.length==0){
              this.$message.warn(removeSelectUserTip);
              return;
          }
          let self_=this;
          if(this.selectedUserRowKeys.length>0){
              this.$confirm({
                  title: tipTitle,
                  content: confirmRemove,
                  okText: tipOk,
                  cancelText: tipCancel,
                  onOk() {
                      self_.unjoin(self_.selectedUserRowKeys.join(','));
                  },
                  onCancel() {},
              });
          }

      },
      unjoin(userIds){
        if (!this.groupId) {
          notification.error({
            message: this.$ti18('rxMsa.errorTip','错误'),
            description: this.i18n('msa.unjoinTips','请选择用户组!')
          })
          return
        }
        const scopeThis=this
        OsRelInstApi.unjoinRelInst({ids: userIds, relTypeId: this.relTypeId, groupId: this.groupId}).then(res => {
          if (res.success && res.code == 200) {
            scopeThis.init()
            scopeThis.selectedUserRowKeys = []
          }
        })
      },
      modifyPwd(record){
          var self=this;
          Util.open({
              component:OsUserUpdatePwd,
              curVm:self,
              widthHeight:['800px','400px'],
              title:this.i18n('list.changePwd','修改密码'),
              data:{userId:record.party2,individual:false}
          },function (action){
          });
      },
        editAdmin(record){
            //组织分级管理,编辑公司管理员
            var self_=this;
            Dialog.openGroupDialog({
                curVm: this,data:{isGrade:true,single:false,dimId:'2',showDimId:true}, widthHeight: ['800px','600px']
            },function(self,groups){
                var osGradeAdminAndRole ={
                    gradeAdminId:record.id,
                    osGradeRole:[]
                };
                for(var i=0;i<groups.length;i++){
                    var obj = {};
                    obj.adminId = record.id;
                    obj.groupId = groups[i].groupId;
                    obj.name = groups[i].name;
                    osGradeAdminAndRole.osGradeRole.push(obj);
                }
                OsGradeAdminApi.updateRole(osGradeAdminAndRole).then(res=>{
                    self.init();
                });
            })
        }
    },
    watch: {
      'groupId'() {
        this.init()
        // 用户组变化时，页码也要回到第一页
        this.page = 1
      },
      'action': function (val, oldVal) {
        if (val == 'ok') {
          this.init()
        }
      }
    }
  }
</script>

<style scoped>
.user-list-fit{
    padding:0 0 10px 0;
}
</style>
